package org.unisannio.remotepicture;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Display;
import android.view.Menu;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.RelativeLayout;

public class RemotePictureActivity extends Activity {
	
	private final String PIC_FILENAME="nomeFileOriginario.jpg";
	private String PIC_PATH=PIC_FILENAME;
	private static final String TAG="OriginalActivity";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_remote_picture);
        
        System.out.println("START CAMERA");
		Intent newIntent = new Intent("android.media.action.IMAGE_CAPTURE");
		File file = new File(getExternalFilesDir(null),	PIC_FILENAME);
		Uri fileUri = Uri.fromFile(file); // create a file to save the image
		newIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri); // set the image file
//															 name
		PIC_PATH=file.getAbsolutePath();
		this.startActivityForResult(newIntent, 1024);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_remote_picture, menu);
        return true;
    }
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    	super.onActivityResult(requestCode, resultCode, data);
    	
    	// Get the image we want to work with from a URL
    	Bitmap myBitmap = this.getBitmap(PIC_PATH);

    	// find the width and height of the screen:
    	Display d = getWindowManager().getDefaultDisplay();
    	int x = d.getWidth();
    	int y = d.getHeight();

    	// get a reference to the ImageView component that will display the image:
    	ImageView imageView=new ImageView(this);

    	// scale it to fit the screen, x and y swapped because my image is wider than it is tall
    	Bitmap scaledBitmap = Bitmap.createScaledBitmap(myBitmap, y, x, true);

    	// create a matrix object
    	Matrix matrix = new Matrix();
    	matrix.postRotate(90); // clockwise by 90 degrees

    	// create a new bitmap from the original using the matrix to transform the result
    	Bitmap rotatedBitmap = Bitmap.createBitmap(scaledBitmap , 0, 0, scaledBitmap .getWidth(), scaledBitmap .getHeight(), matrix, true);

    	// display the rotated bitmap
    	imageView.setImageBitmap(rotatedBitmap);
    	
        RelativeLayout layout=new RelativeLayout(this);
        layout.addView(imageView);
        this.setContentView(layout);
    }

    
    private Bitmap getBitmap(String path) {
//		Uri uri = Uri.parse(path);
		InputStream in = null;
		try {
		    final int IMAGE_MAX_SIZE = 1200000; // 1.2MP
		    in = new FileInputStream(new File(path));
//		    in = mContentResolver.openInputStream(uri);

		    // Decode image size
		    BitmapFactory.Options o = new BitmapFactory.Options();
		    o.inJustDecodeBounds = true;
		    BitmapFactory.decodeStream(in, null, o);
		    in.close();



		    int scale = 1;
		    while ((o.outWidth * o.outHeight) * (1 / Math.pow(scale, 2)) > 
		          IMAGE_MAX_SIZE) {
		       scale++;
		    }
		    Log.d(TAG, "scale = " + scale + ", orig-width: " + o.outWidth + ",  orig-height: " + o.outHeight);

		    Bitmap b = null;
		    in = new FileInputStream(new File(path));
		    if (scale > 1) {
		        scale--;
		        // scale to max possible inSampleSize that still yields an image
		        // larger than target
		        o = new BitmapFactory.Options();
		        o.inSampleSize = scale;
		        b = BitmapFactory.decodeStream(in, null, o);

		        // resize to desired dimensions
		        int height = b.getHeight();
		        int width = b.getWidth();
		        Log.d(TAG, "1th scale operation dimenions - width: " + width + ",  height: " + height);

		        double y = Math.sqrt(IMAGE_MAX_SIZE
		                / (((double) width) / height));
		        double x = (y / height) * width;

		        Bitmap scaledBitmap = Bitmap.createScaledBitmap(b, (int) x, 
		           (int) y, true);
		        b.recycle();
		        b = scaledBitmap;

		        System.gc();
		    } else {
		        b = BitmapFactory.decodeStream(in);
		    }
		    in.close();

		    Log.d(TAG, "bitmap size - width: " +b.getWidth() + ", height: " + 
		       b.getHeight());
		    return b;
		} catch (IOException e) {
		    Log.e(TAG, e.getMessage(),e);
		    return null;
		}
	}
    
}
